#!/usr/bin/env python3
"""
EndoSight-UC AI推理服务器 V3.0 快速启动脚本
包含配置验证、依赖检查和安全确认
"""

import os
import sys
import subprocess
import time
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        return False
    print(f"✅ Python版本检查通过: {sys.version}")
    return True

def check_dependencies():
    """检查关键依赖"""
    required_packages = [
        'fastapi',
        'uvicorn',
        'torch',
        'transformers',
        'slowapi',
        'magic',
        'pydantic'
    ]

    missing_packages = []
    for package in required_packages:
        try:
            if package == 'magic':
                import magic
            else:
                __import__(package)
        except ImportError:
            missing_packages.append(package)

    if missing_packages:
        print(f"❌ 缺少依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False

    print("✅ 依赖检查通过")
    return True

def check_model_file():
    """检查模型文件"""
    model_path = Path("uc_model/final_weights/uceis_best_model.pth")
    if not model_path.exists():
        print(f"❌ 模型文件不存在: {model_path}")
        return False

    file_size = model_path.stat().st_size / (1024 * 1024)  # MB
    print(f"✅ 模型文件检查通过: {model_path} ({file_size:.1f}MB)")
    return True

def check_config():
    """检查配置文件"""
    env_file = Path(".env")
    if not env_file.exists():
        print("⚠️  .env文件不存在，将使用默认配置")
        print("建议复制 .env.example 为 .env 并配置")
        return True

    # 检查关键配置
    with open('.env') as f:
        content = f.read()

    warnings = []
    if 'your-secret-key-change-in-production' in content and 'production' in content:
        warnings.append("生产环境使用了默认密钥")

    if 'ALLOWED_ORIGINS=*' in content:
        warnings.append("CORS配置不安全 (使用了 *)")

    if warnings:
        print("⚠️  配置警告:")
        for warning in warnings:
            print(f"   - {warning}")
    else:
        print("✅ 配置检查通过")

    return True

def check_core_modules():
    """检查核心安全模块"""
    core_modules = [
        'core/__init__.py',
        'core/config.py',
        'core/security.py',
        'core/schemas.py'
    ]

    missing_modules = []
    for module in core_modules:
        if not Path(module).exists():
            missing_modules.append(module)

    if missing_modules:
        print(f"❌ 缺少核心模块: {', '.join(missing_modules)}")
        return False

    print("✅ 核心模块检查通过")
    return True

def run_server():
    """启动服务器"""
    print("\n🚀 启动EndoSight-UC V3.0安全服务器...")
    print("=" * 50)

    # 设置环境变量
    env = os.environ.copy()
    env['PYTHONPATH'] = str(Path.cwd())

    try:
        # 启动服务器
        process = subprocess.Popen([
            sys.executable, 'inference_server_v3.py'
        ], env=env)

        print("服务器正在启动...")
        print("按 Ctrl+C 停止服务器")
        print("=" * 50)

        # 等待进程
        process.wait()
        return True

    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
        if 'process' in locals():
            process.terminate()
        return True
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        return False

def main():
    """主函数"""
    print("EndoSight-UC AI推理服务器 V3.0 安全启动检查")
    print("=" * 50)

    checks = [
        ("Python版本", check_python_version),
        ("依赖包", check_dependencies),
        ("模型文件", check_model_file),
        ("配置文件", check_config),
        ("核心模块", check_core_modules),
    ]

    all_passed = True
    for check_name, check_func in checks:
        print(f"\n🔍 检查{check_name}...")
        if not check_func():
            all_passed = False

    if not all_passed:
        print("\n❌ 启动检查失败，请修复上述问题后重试")
        return 1

    print("\n✅ 所有检查通过，准备启动服务器")

    # 询问是否继续
    try:
        response = input("\n是否现在启动服务器? (y/n): ").strip().lower()
        if response in ['y', 'yes', '是']:
            return 0 if run_server() else 1
        else:
            print("启动已取消")
            return 0
    except KeyboardInterrupt:
        print("\n启动已取消")
        return 0

if __name__ == "__main__":
    exit(main())